<!DOCTYPE html>
<html>
  <!-- meta/link... -->
  



<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <!-- Global site tag (gtag.js) - Google Analytics -->


  <title>java多线程加速遍历解析 | symkmk123</title>

  <link rel="icon" type="image/x-icon, image/vnd.microsoft.icon" href="/favicon.ico">
  <link rel="stylesheet" href="https://at.alicdn.com/t/font_1911880_c1nvbyezg17.css">
  <link href="https://cdn.jsdelivr.net/gh/inkss/fontawesome@5.15.3/css/all.min.css" rel="stylesheet">

  
    <script>
        var themeModelId = '';
        if (themeModelId) {
            localStorage.setItem('modelId', themeModelId);
        }
    </script>
    
    <script src="https://cdn.jsdelivr.net/gh/yuang01/live2d-widget@latest/autoload.js"></script>
    <script>
        var live2dOpen = eval('true') || false;
        if (!live2dOpen) {
            localStorage.setItem('waifu-display', 1609323474481);
        }
    </script>
  
  
  
<link rel="stylesheet" href="/css/animate.min.css">

  
<link rel="stylesheet" href="/css/style.css">

  
  
    
<link rel="stylesheet" href="/js/fancybox/jquery.fancybox.min.css">

  
  
  <style>
        @media (max-width: 992px) {
            #waifu {
                display: none;
            }
        }
    </style>
    <script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
    <link href="//cdn.bootcss.com/pace/1.0.2/themes/pink/pace-theme-flash.css" rel="stylesheet">

    

    <!-- import link -->
    
        
            
        
            
        
    
    <!-- import script -->
    
        
            
        
            
        
    

<meta name="generator" content="Hexo 5.4.0"></head>

  
  <!-- 依赖于jquery和vue -->
  <script src="/js/jquery3.5.1.js"></script>
  <script src="/js/vue2.6.11.js"></script>
  
  <body>
    <!-- 预加载动画 -->
    <!-- 页面预加载动画 -->

<div id='loader'>
  <link rel="stylesheet" href="/js/loaded/index.css" >
  <div class="loading-left-bg"></div>
  <div class="loading-right-bg"></div>
  <div class="spinner-box">
    <div class="configure-border-1">
      <div class="configure-core"></div>
    </div>
    <div class="configure-border-2">
      <div class="configure-core"></div>
    </div>
    <div class="loading-word">加载中...</div>
  </div>
</div>

<script>
  var endLoading = function () {
    document.body.style.overflow = 'auto';
    document.getElementById('loader').classList.add("loading");
  }
  window.addEventListener('DOMContentLoaded',endLoading);
  
</script>

    
    <!-- 判断是否为暗黑风格 -->
    <!-- 判断是否为黑夜模式 -->
<script>
  let isDark = JSON.parse(localStorage.getItem('dark')) || JSON.parse('false');

  if (isDark) {
    $(document.body).addClass('darkModel');
  }
</script>

    <!-- 头部导航等 -->
    
<header class="header " id="navHeader"
  style="position: fixed;
  left: 0; top: 0; z-index: 10;width: 100%;"
>
  <div class="header-content">
    <div class="bars">
      <div id="appDrawer" class="sidebar-image">
  <div class="drawer-box-icon">
    <i class="fas fa-bars" aria-hidden="true" @click="showDialogDrawer"></i>
  </div>
  
  <transition name="fade">
    <div class="drawer-box_mask" v-cloak style="display: none;" v-show="visible" @click.self="cancelDialogDrawer">
    </div>
  </transition>
  <div class="drawer-box" :class="{'active': visible}">
    <div class="drawer-box-head bg-color">
      <img class="drawer-box-head_logo lazyload placeholder" src="/medias/logo.png" class="lazyload placeholder" data-srcset="/medias/logo.png" srcset="https://img2.baidu.com/it/u=2037979560,2772131037&fm=26&fmt=auto&gp=0.jpg" alt="logo">
      <h3 class="drawer-box-head_title">symkmk123</h3>
      <h5 class="drawer-box-head_desc"></h5>
    </div>
    
    <div class="drawer-box-content">
      <ul class="drawer-box-content_menu">
        
          
            <li class="drawer-box-content_item" style="position: relative;">
              
                <a href="/" class="drawer-menu-item-link">
                  
                    <i class="fa fa-home" aria-hidden="true"></i>
                  
                  <span class="name">首页</span>
                </a>
              
            </li>
          
            <li class="drawer-box-content_item" style="position: relative;">
              
                <a href="/archives" class="drawer-menu-item-link">
                  
                    <i class="fa fa-archive" aria-hidden="true"></i>
                  
                  <span class="name">归档</span>
                </a>
              
            </li>
          
            <li class="drawer-box-content_item" style="position: relative;">
              
                <a href="/tags" class="drawer-menu-item-link">
                  
                    <i class="fa fa-tags" aria-hidden="true"></i>
                  
                  <span class="name">标签</span>
                </a>
              
            </li>
          
            <li class="drawer-box-content_item" style="position: relative;">
              
                <a href="/categories" class="drawer-menu-item-link">
                  
                    <i class="fa fa-bookmark" aria-hidden="true"></i>
                  
                  <span class="name">分类</span>
                </a>
              
            </li>
          
            <li class="drawer-box-content_item" style="position: relative;">
              
                <a href="/about" class="drawer-menu-item-link">
                  
                    <i class="fa fa-user" aria-hidden="true"></i>
                  
                  <span class="name">关于</span>
                </a>
              
            </li>
          
        
        
          <li class="drawer-box-content_item">
            <a target="_blank" rel="noopener" href="https://gitee.com/symkmk123">
              <i class="fas fa-github" aria-hidden="true"></i>
              <span>Github</span>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</div>

<script>
  var body = document.body || document.documentElement || window;
  var vm = new Vue({
    el: '#appDrawer',
    data: {
      visible: false,
      top: 0,
      openArr: [],
    },
    computed: {
    },
    mounted() {
    },
    methods: {
      isOpen(index) {
        if (this.openArr.includes(index)) {
          return true;
        } else {
          return false;
        }
      },
      openOrCloseMenu(curIndex) {
        const index = this.openArr.indexOf(curIndex);
        if (index !== -1) {
          this.openArr.splice(index, 1);
        } else {
          this.openArr.push(curIndex);
        }
      },
      showDialogDrawer() {
        this.visible = true;
        // 防止页面滚动，只能让弹框滚动
        this.top = $(document).scrollTop()
        body.style.cssText = 'width: 100%; height: 100%;overflow: hidden;';
      },
      cancelDialogDrawer() {
        this.visible = false;
        body.removeAttribute('style');
        $(document).scrollTop(this.top)
      }
    },
    created() {}
  })
</script>

    </div>
    <div class="blog-title" id="author-avatar">
      
        <div class="avatar">
          <img src="/medias/logo.png" class="lazyload placeholder" data-srcset="/medias/logo.png" srcset="https://img2.baidu.com/it/u=2037979560,2772131037&fm=26&fmt=auto&gp=0.jpg" alt="logo">
        </div>
      
      <a href="/" class="logo">symkmk123</a>
    </div>
    <nav class="navbar">
      <ul class="menu">
        
          
            <li class="menu-item" style="position: relative;">
              
                <a href="/" class="menu-item-link" title="首页">
                  
                    <i class="fa fa-home" aria-hidden="true"></i>
                  
                  <span class="name">首页</span>
                </a>
              
            </li>
          
            <li class="menu-item" style="position: relative;">
              
                <a href="/archives" class="menu-item-link" title="归档">
                  
                    <i class="fa fa-archive" aria-hidden="true"></i>
                  
                  <span class="name">归档</span>
                </a>
              
            </li>
          
            <li class="menu-item" style="position: relative;">
              
                <a href="/tags" class="menu-item-link" title="标签">
                  
                    <i class="fa fa-tags" aria-hidden="true"></i>
                  
                  <span class="name">标签</span>
                </a>
              
            </li>
          
            <li class="menu-item" style="position: relative;">
              
                <a href="/categories" class="menu-item-link" title="分类">
                  
                    <i class="fa fa-bookmark" aria-hidden="true"></i>
                  
                  <span class="name">分类</span>
                </a>
              
            </li>
          
            <li class="menu-item" style="position: relative;">
              
                <a href="/about" class="menu-item-link" title="关于">
                  
                    <i class="fa fa-user" aria-hidden="true"></i>
                  
                  <span class="name">关于</span>
                </a>
              
            </li>
          
        
      </ul>
      
      
        <div id="appSearch">
  <div class="search"  @click="showDialog()"><i class="fas fa-search" aria-hidden="true"></i></div>
  <transition name="fade">
    <div class="message-box_wrapper" style="display: none;" v-cloak v-show="dialogVisible" @click.self="cancelDialogVisible()">
      <div class="message-box animated bounceInDown">
        <h2>
          <span>
            <i class="fas fa-search" aria-hidden="true"></i>
            <span class="title">本地搜索</span>
          </span>
          <i class="fas fa-times close" pointer style="float:right;" aria-hidden="true" @click.self="cancelDialogVisible()"></i>
        </h2>
        <form class="site-search-form">
          <input type="text"
            placeholder="请输入关键字"
            id="local-search-input" 
            @click="getSearchFile()"
            class="st-search-input"
            v-model="searchInput"
          />
        </form>
        <div class="result-wrapper">
          <div id="local-search-result" class="local-search-result-cls"></div>
        </div>
      </div>
    </div>
  </transition>
</div>
<script src="/js/local_search.js"></script>
<script>
  var body = document.body || document.documentElement || window;
  var vm = new Vue({
    el: '#appSearch',
    data: {
      dialogVisible: false,
      searchInput: '',
      top: 0,
    },
    computed: {
    },
    mounted() {
      window.addEventListener('pjax:complete', () => {
        this.cancelDialogVisible();
      })
    },
    methods: {
      showDialog() {
        this.dialogVisible = true;
        // 防止页面滚动，只能让弹框滚动
        this.top = $(document).scrollTop()
        body.style.cssText = 'overflow: hidden;';
      },
      getSearchFile() {
        if (!this.searchInput) {
          getSearchFile("/search.xml");
        }
      },
      cancelDialogVisible() {
        this.dialogVisible = false;
        body.removeAttribute('style');
        $(document).scrollTop(this.top)
      },
    },
    created() {}
  })
</script>
<!-- 解决刷新页面闪烁问题，可以在元素上添加display: none, 或者用vue.extend方法，详情：https://blog.csdn.net/qq_31393401/article/details/81017912 -->
<!-- 下面是搜索基本写法 -->
<!-- <script type="text/javascript" id="local.search.active">
  var inputArea = document.querySelector("#local-search-input");
  inputArea.onclick   = function(){ getSearchFile(); this.onclick = null }
  inputArea.onkeydown = function(){ if(event.keyCode == 13) return false }
</script> -->

      

    </nav>
  </div>
  
    <a target="_blank" rel="noopener" href="https://gitee.com/symkmk123" class="github-corner color-primary" aria-label="View source on GitHub"><svg width="60" height="60" viewBox="0 0 250 250" style="fill:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
  
  

    <!-- 当头部导航设置为背景透明的时候  -->
    
      <script src="/js/header/index.js" data-pjax></script>
    
</header>

    <!-- 需要在上面加载的js -->
    <script>
  function loadScript(src, cb) {
    return new Promise(resolve => {
      setTimeout(function () {
        var HEAD = document.getElementsByTagName("head")[0] || document.documentElement;
        var script = document.createElement("script");
        script.setAttribute("type", "text/javascript");
        if (cb) {
          if (JSON.stringify(cb)) {
            for (let p in cb) {
              if (p == "onload") {
                script[p] = () => {
                  cb[p]()
                  resolve()
                }
              } else {
                script[p] = cb[p]
                script.onload = resolve
              }
            }
          } else {
            script.onload = () => {
              cb()
              resolve()
            };
          }
        } else {
          script.onload = resolve
        }
        script.setAttribute("src", src);
        HEAD.appendChild(script);
      });
    });
  }

  //https://github.com/filamentgroup/loadCSS
  var loadCSS = function (href, before, media, attributes) {
    return new Promise(resolve => {
      setTimeout(function () {
        var link = document.createElement('link');
        link.rel = "stylesheet";
        link.href = src;
        link.onload = resolve;
        document.getElementsByTagName("head")[0].appendChild(link);
      });
    });
  };

</script> 

<!-- 轮播图所需要的js -->
<script src="/js/swiper/swiper.min.js"></script>
<script src="/js/swiper/vue-awesome-swiper.js"></script>
<script src="/js/swiper/swiper.animate1.0.3.min.js"></script>


  <script src="/js/vue-typed-js/index.js"></script>


<!-- 首页的公告滚动插件的js需要重新加载 -->
<script src="/js/vue-seamless-scroll/index.js"></script>

<!-- 打字机效果js -->
<script src="https://cdn.jsdelivr.net/npm/typed.js@2.0.11"></script>


    <!-- 内容区域 -->
    <div id="safearea">
      <main class="main" id="pjax-container" style="margin-top: 0;">
        
 <!-- prismjs 代码高亮 -->
 


<div class="bg-dark-floor" style="position: fixed;left: 0;top: 0;width: 100%;height: 100%;z-index: -1;"></div>

<!-- 文章详情页顶部图片和标题 -->




<div class="post-detail-header" id="thumbnail_canvas" style="background-repeat: no-repeat; background-size: cover; 
  background-position: center center;position: relative;background-image:url('/medias/10.jpg')">
  <div class="post-detail-header-mask"></div>
  <canvas id="header_canvas"style="position:absolute;bottom:0;pointer-events:none;"></canvas>
  
  <div class="post-detail-header_info-box">
    <div class="title-box">
      <span class="title">
        java多线程加速遍历解析
      </span>
    </div>
    
    
      
        <span class="post-detail-header_date">
          <i class="fas fa-calendar"></i> 发表于：2022-02-14 |
        </span>
      

      
        <span class="post-detail-header_categories">
          <i class="iconfont iconbookmark1"></i> 分类：
          
            <a href="/categories/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" class="post-detail-header_category">
              多线程
            </a>
          
        </span>
      

      
        <div class="post-detail-header_wordcount">
          <span class="totalcount">
            <i class="fas fa-file-text-o"></i> 字数统计: 2k |
          </span>
  
          <span class="min2read">
            <i class="fas fa-clock"></i> 阅读时长: 10分钟 |
          </span>
  
          
            <span class="reading">
              <i class="fas fa-eye"></i> 阅读量：<span id="busuanzi_value_page_pv"></span>
            </span>
          
        </div>
      
    
  </div>
  
  
    <script src="/js/bubble/bubble.js"></script>
  
</div>



<div class="row justify-position">
  <div class="main-content">
    <article class="post post-detail">
      <div class="post-content">
        <h1 id="原始需求"><a href="#原始需求" class="headerlink" title="原始需求"></a>原始需求</h1><p>导出医生记录</p>
<p>//按照患者id分组，组内按照就诊时间升序</p>
<p><img src="https://syguli-file.oss-cn-beijing.aliyuncs.com/img/20220407092101.png" class="lazyload placeholder" data-srcset="https://syguli-file.oss-cn-beijing.aliyuncs.com/img/20220407092101.png" srcset="https://img2.baidu.com/it/u=2037979560,2772131037&fm=26&fmt=auto&gp=0.jpg"></p>
<p>上面是耗时久的代码，每次导出一万五百条数据大概需要五六分钟才出结果，其中es里存的是json格式的数据，每次还需要解析。</p>
<h2 id="初步优化"><a href="#初步优化" class="headerlink" title="初步优化"></a>初步优化</h2><p>初步优化思路是：将json插入的时候就解析好存入es里每次查询导出数据的时候不用用的时候在解析。这边自动解析使用一个服务canal监听MySQL，将解析json这部分的代码拆出来放在这里。</p>
<p>初步优化这里大概还是需要两分钟才能出结果</p>
<p><img src="https://syguli-file.oss-cn-beijing.aliyuncs.com/img/20220407092348.png" class="lazyload placeholder" data-srcset="https://syguli-file.oss-cn-beijing.aliyuncs.com/img/20220407092348.png" srcset="https://img2.baidu.com/it/u=2037979560,2772131037&fm=26&fmt=auto&gp=0.jpg"></p>
<p>发现主要耗时的操作就是for里的代码，每个用户都需要一个个去查7次es(因为有七个问卷，将每个问卷拆分成了7个es的索引)，这边是单线程的，使用CompletableFuture优化成不并行的任务，这边由于操作没有返回值不需要join等待，（加了join速度不是很快）</p>
<p><img src="https://syguli-file.oss-cn-beijing.aliyuncs.com/img/20220407092412.png" class="lazyload placeholder" data-srcset="https://syguli-file.oss-cn-beijing.aliyuncs.com/img/20220407092412.png" srcset="https://img2.baidu.com/it/u=2037979560,2772131037&fm=26&fmt=auto&gp=0.jpg"></p>
<p>经过测试速度提升了快一倍，但还在继续寻找优化方法</p>
<p><img src="https://syguli-file.oss-cn-beijing.aliyuncs.com/img/20220407092436.png" class="lazyload placeholder" data-srcset="https://syguli-file.oss-cn-beijing.aliyuncs.com/img/20220407092436.png" srcset="https://img2.baidu.com/it/u=2037979560,2772131037&fm=26&fmt=auto&gp=0.jpg"></p>
<h3 id="CountDownLatch优化"><a href="#CountDownLatch优化" class="headerlink" title="CountDownLatch优化"></a>CountDownLatch优化</h3><p>观察核心耗时代码发现，最主要的原因在for循环这，将Map&lt;Long, List<ESDoctorRecord>&gt; patientIdGroupMap这个map写一个方法等分成list，用多线程去操作list去写数据。</p>
<p><img src="https://syguli-file.oss-cn-beijing.aliyuncs.com/img/20220407092515.png" class="lazyload placeholder" data-srcset="https://syguli-file.oss-cn-beijing.aliyuncs.com/img/20220407092515.png" srcset="https://img2.baidu.com/it/u=2037979560,2772131037&fm=26&fmt=auto&gp=0.jpg"></p>
<p><img src="https://syguli-file.oss-cn-beijing.aliyuncs.com/img/20220407093050.png" class="lazyload placeholder" data-srcset="https://syguli-file.oss-cn-beijing.aliyuncs.com/img/20220407093050.png" srcset="https://img2.baidu.com/it/u=2037979560,2772131037&fm=26&fmt=auto&gp=0.jpg"></p>
<p>这边自己写的时候有很多坑，自己一步步调试才避免，首先是多线程往list写的问题，需要一个计数器去将线程数减一，这个之前的想法是使用一个CyclicBarrier栅栏去等待所有线程结束在一起执行</p>
<p><img src="https://syguli-file.oss-cn-beijing.aliyuncs.com/img/20220407093130.png" class="lazyload placeholder" data-srcset="https://syguli-file.oss-cn-beijing.aliyuncs.com/img/20220407093130.png" srcset="https://img2.baidu.com/it/u=2037979560,2772131037&fm=26&fmt=auto&gp=0.jpg"></p>
<p>在用 <code>Thread().start()</code> 测试上面的代码是没有问题的，但是改成用自定义的定长的线程池的时候发现有死锁的问题！！</p>
<p><img src="https://syguli-file.oss-cn-beijing.aliyuncs.com/img/20220407093157.png" class="lazyload placeholder" data-srcset="https://syguli-file.oss-cn-beijing.aliyuncs.com/img/20220407093157.png" srcset="https://img2.baidu.com/it/u=2037979560,2772131037&fm=26&fmt=auto&gp=0.jpg"></p>
<p>因为自定义的是定长线程池，所以会卡在这</p>
<p><img src="https://syguli-file.oss-cn-beijing.aliyuncs.com/img/20220407093230.png" class="lazyload placeholder" data-srcset="https://syguli-file.oss-cn-beijing.aliyuncs.com/img/20220407093230.png" srcset="https://img2.baidu.com/it/u=2037979560,2772131037&fm=26&fmt=auto&gp=0.jpg"></p>
<p>改用CountDownLatch，将主线程阻塞直到所有的解析任务都被执行完成。但是测试的时候最后总list数量一开始总是不对，之前以为是join方法没有阻塞就又换了种多线程的方法，但仔细观察了下方法发现是开启多个线程往list里添加的list的类型有问题。</p>
<p><img src="https://syguli-file.oss-cn-beijing.aliyuncs.com/img/20220407093320.png" class="lazyload placeholder" data-srcset="https://syguli-file.oss-cn-beijing.aliyuncs.com/img/20220407093320.png" srcset="https://img2.baidu.com/it/u=2037979560,2772131037&fm=26&fmt=auto&gp=0.jpg"></p>
<h3 id="用CompletableFuture优化"><a href="#用CompletableFuture优化" class="headerlink" title="用CompletableFuture优化"></a>用CompletableFuture优化</h3><p>一开始没注意到这个问题，又多写了一种开启多线程的方法，也是用CompletableFuture</p>
<p><img src="https://syguli-file.oss-cn-beijing.aliyuncs.com/img/20220407093345.png" class="lazyload placeholder" data-srcset="https://syguli-file.oss-cn-beijing.aliyuncs.com/img/20220407093345.png" srcset="https://img2.baidu.com/it/u=2037979560,2772131037&fm=26&fmt=auto&gp=0.jpg"></p>
<p>最后在测试服务器上的时间:</p>
<p><img src="https://syguli-file.oss-cn-beijing.aliyuncs.com/img/20220407093401.png" class="lazyload placeholder" data-srcset="https://syguli-file.oss-cn-beijing.aliyuncs.com/img/20220407093401.png" srcset="https://img2.baidu.com/it/u=2037979560,2772131037&fm=26&fmt=auto&gp=0.jpg"></p>
<p>附代码：</p>
<ul>
<li>CompletableFuture</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">export2</span><span class="params">(<span class="keyword">int</span> exportType, Long livingId, String timeRange, HttpServletRequest request, HttpServletResponse response)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line"><span class="comment">//        QueryParaWrapper&lt;TDoctorRecord&gt; tDoctorRecordQueryParams = new QueryParaWrapper&lt;&gt;();</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//        TDoctorRecord qdoctorRecord = new TDoctorRecord();</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//        qdoctorRecord.setHospitalId(livingId);</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//        tDoctorRecordQueryParams.setEntity(qdoctorRecord);</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//        Result&lt;List&lt;TDoctorRecord&gt;&gt; listProduceResultModel = tDoctorRecordInterface.queryTDoctorRecordList(tDoctorRecordQueryParams);</span></span><br><span class="line"></span><br><span class="line"> </span><br><span class="line"></span><br><span class="line">        <span class="comment">//改为从es获取医生记录</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">long</span> start1 = System.currentTimeMillis();</span><br><span class="line"></span><br><span class="line">        List&lt;ESDoctorRecord&gt; tDoctorRecord = exportHelp.getTDoctorRecord(livingId);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (CollectionUtils.isEmpty(tDoctorRecord)) &#123;</span><br><span class="line"></span><br><span class="line">            ExportUtils.responseData(response);</span><br><span class="line"></span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">long</span> start2 = System.currentTimeMillis();</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;查询1，耗时：&quot;</span> + (start2 - start1) + <span class="string">&quot;ms&quot;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//        tDoctorRecord.stream().forEach(a-&gt;&#123;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//            TDoctorRecord tr = new TDoctorRecord();</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//            tr.</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//        &#125;);</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//        List&lt;TDoctorRecord&gt; tDoctorRecordList = listProduceResultModel.getData();</span></span><br><span class="line"></span><br><span class="line">        Result&lt;List&lt;UserAndPatientVo&gt;&gt; produceResultModel = tUserInterface.ExportPatient(livingId);</span><br><span class="line"></span><br><span class="line">        List&lt;UserAndPatientVo&gt; patientData = produceResultModel.getData();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (CollectionUtils.isEmpty(tDoctorRecord) || CollectionUtils.isEmpty(patientData)) &#123;</span><br><span class="line"></span><br><span class="line">            ExportUtils.responseData(response);</span><br><span class="line"></span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        tDoctorRecord = tDoctorRecord.stream().filter(a -&gt; !Constant.TEST_HOSPITAL.contains(a.getHospitalId())).collect(Collectors.toList());</span><br><span class="line"></span><br><span class="line">        System.out.println(tDoctorRecord.size() + <span class="string">&quot;----&quot;</span>);</span><br><span class="line"></span><br><span class="line">        Map&lt;Long, List&lt;UserAndPatientVo&gt;&gt; patientMap = patientData.stream().collect(Collectors.groupingBy(UserAndPatientVo::getUserId));</span><br><span class="line"></span><br><span class="line">        <span class="comment">//按照患者id分组，组内按照就诊时间升序</span></span><br><span class="line"></span><br><span class="line">        Map&lt;Long, List&lt;ESDoctorRecord&gt;&gt; patientIdGroupMap = tDoctorRecord.stream().collect(Collectors.groupingBy(ESDoctorRecord::getUserId));</span><br><span class="line"></span><br><span class="line">        <span class="comment">//注意！！多线程写</span></span><br><span class="line"></span><br><span class="line">        List&lt;DoctorRedExportVo&gt; tDoctorRecords = Collections.synchronizedList(<span class="keyword">new</span> ArrayList&lt;&gt;());</span><br><span class="line"></span><br><span class="line">        <span class="keyword">long</span> start = System.currentTimeMillis();</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;查询2，耗时：&quot;</span> + (start - start1) + <span class="string">&quot;ms&quot;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//        for (Map.Entry&lt;Long, List&lt;ESDoctorRecord&gt;&gt; entry : patientIdGroupMap.entrySet()) &#123;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//        List&lt;Map&lt;Long, List&lt;ESDoctorRecord&gt;&gt;&gt; maps = new LinkedList&lt;&gt;();</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//        maps.add(patientIdGroupMap);</span></span><br><span class="line"></span><br><span class="line">        AtomicInteger i = <span class="keyword">new</span> AtomicInteger(<span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">        List&lt;Map&lt;Long, List&lt;ESDoctorRecord&gt;&gt;&gt; maps = CollUtils.mapChunk(patientIdGroupMap, patientIdGroupMap.size() / <span class="number">15</span>+<span class="number">1</span>);</span><br><span class="line"></span><br><span class="line">        CompletableFuture[] cfs = maps.parallelStream().map(n -&gt; CompletableFuture.runAsync(() -&gt; cal(livingId, patientMap, n, tDoctorRecords),excelEventPool)</span><br><span class="line"></span><br><span class="line">                .whenComplete((v, e) -&gt; &#123;</span><br><span class="line"></span><br><span class="line">            System.out.println(<span class="string">&quot;任务&quot;</span> + i.incrementAndGet()+Thread.currentThread().getName());</span><br><span class="line"></span><br><span class="line">        &#125;)</span><br><span class="line"></span><br><span class="line">        ).toArray(CompletableFuture[]::<span class="keyword">new</span>);</span><br><span class="line"></span><br><span class="line">        CompletableFuture.allOf(cfs).join();</span><br><span class="line"></span><br><span class="line"> </span><br><span class="line"></span><br><span class="line">        <span class="comment">//</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//        AtomicInteger i = new AtomicInteger(1);</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//        List&lt;CompletableFuture&lt;Void&gt;&gt; completableFutureList = new LinkedList&lt;&gt;();</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//        completableFutureList=maps.parallelStream().map(n -&gt; &#123;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//            return CompletableFuture.runAsync(() -&gt; &#123;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//                cal(livingId, patientMap, n, tDoctorRecords);</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//                System.out.println(i.getAndIncrement());</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//            &#125;);</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//        &#125;).collect(Collectors.toList());</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//        CompletableFuture&lt;Void&gt; headerFuture = CompletableFuture.allOf(completableFutureList.toArray(new CompletableFuture[]&#123;&#125;));</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//        try &#123;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//            headerFuture.join();</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//        &#125; catch (Exception ex) &#123;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//            System.out.println(&quot;done count: &quot; + i.get());</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//        &#125;</span></span><br><span class="line"></span><br><span class="line">        System.out.println(tDoctorRecords.size() + <span class="string">&quot;--===--&quot;</span>);</span><br><span class="line"></span><br><span class="line">        tDoctorRecords.sort(Comparator.comparing(DoctorRedExportVo::getUserId).thenComparing(DoctorRedExportVo::getVisitTime));</span><br><span class="line"></span><br><span class="line">        <span class="keyword">long</span> end = System.currentTimeMillis();</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;方法，耗时：&quot;</span> + (end - start) + <span class="string">&quot;ms&quot;</span>);</span><br><span class="line"></span><br><span class="line">        export(request, response, tDoctorRecords);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">long</span> end2 = System.currentTimeMillis();</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;方法2，耗时：&quot;</span> + (end2 - end) + <span class="string">&quot;ms&quot;</span>);</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;总，耗时：&quot;</span> + (end2 - start1) + <span class="string">&quot;ms&quot;</span>);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">cal</span><span class="params">(Long livingId, Map&lt;Long, List&lt;UserAndPatientVo&gt;&gt; patientMap, Map&lt;Long, List&lt;ESDoctorRecord&gt;&gt; patientIdGroupMap, List&lt;DoctorRedExportVo&gt; tDoctorRecords )</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        patientIdGroupMap.entrySet().stream().forEach((entry) -&gt; &#123;</span><br><span class="line"></span><br><span class="line">            List&lt;ESDoctorRecord&gt; valList = entry.getValue();</span><br><span class="line"></span><br><span class="line">            valList.sort(Comparator.comparing(ESDoctorRecord::getVisitTime));</span><br><span class="line"></span><br><span class="line">            <span class="keyword">int</span> size = valList.size();</span><br><span class="line"></span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; size; i++) &#123;</span><br><span class="line"></span><br><span class="line">                ESDoctorRecord esDoctorRecord = valList.get(i);</span><br><span class="line"></span><br><span class="line">                List&lt;UserAndPatientVo&gt; patientList = patientMap.get(esDoctorRecord.getUserId());</span><br><span class="line"></span><br><span class="line"> </span><br><span class="line"></span><br><span class="line">                <span class="keyword">if</span> (CollectionUtils.isEmpty(patientList)) &#123;</span><br><span class="line"></span><br><span class="line">                    System.out.println(esDoctorRecord.getId() + <span class="string">&quot;====&quot;</span>);</span><br><span class="line"></span><br><span class="line">                    <span class="keyword">continue</span>;</span><br><span class="line"></span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                DoctorRedExportVo doctorRedExportVo = getWholBasdaiQuestionByUserId(esDoctorRecord);</span><br><span class="line"></span><br><span class="line">                BeanUtils.copyProperties(patientList.get(<span class="number">0</span>), doctorRedExportVo);</span><br><span class="line"></span><br><span class="line">                doctorRedExportVo.setMobile(patientList.get(<span class="number">0</span>).getMobile());</span><br><span class="line"></span><br><span class="line">                doctorRedExportVo.setSymptomsAppearTime(HelpUtils.dateToyyyyMMdd(HelpUtils.yyyyMMddToDate(patientList.get(<span class="number">0</span>).getSymptomsAppearTime())));</span><br><span class="line"></span><br><span class="line">                doctorRedExportVo.setSymptomsAppearTreatTime(HelpUtils.dateToyyyyMMdd(HelpUtils.yyyyMMddToDate(patientList.get(<span class="number">0</span>).getSymptomsAppearTreatTime())));</span><br><span class="line"></span><br><span class="line">                doctorRedExportVo.setSymptomsDiagnosisTime(HelpUtils.dateToyyyyMMdd(HelpUtils.yyyyMMddToDate(patientList.get(<span class="number">0</span>).getSymptomsDiagnosisTime())));</span><br><span class="line"></span><br><span class="line">                doctorRedExportVo.setJoinTime(HelpUtils.dateToyyyyMMdd(HelpUtils.yyyyMMddToDate(patientList.get(<span class="number">0</span>).getJoinTime())));</span><br><span class="line"></span><br><span class="line">                Map&lt;String, String&gt; cacheMap = doctorRedCacheHelp.getFirstJoinHospitalCache(livingId);</span><br><span class="line"></span><br><span class="line">                doctorRedExportVo.setLivingName(cacheMap.get(esDoctorRecord.getUserId().toString()));</span><br><span class="line"></span><br><span class="line">                doctorRedExportVo.setVisitsNum(i + <span class="number">1</span>);</span><br><span class="line"></span><br><span class="line">                doctorRedExportVo.setVisitTime(HelpUtils.dateToyyyyMMdd(esDoctorRecord.getVisitTime()));</span><br><span class="line"></span><br><span class="line">                BeanUtils.copyProperties(esDoctorRecord, doctorRedExportVo);</span><br><span class="line"></span><br><span class="line">                doctorRedExportVo.setSex(ExportHelp.sex(doctorRedExportVo.getSex()));</span><br><span class="line"></span><br><span class="line">                CompletableFuture&lt;Void&gt; f1 = CompletableFuture</span><br><span class="line"></span><br><span class="line">                        .runAsync(() -&gt; &#123;</span><br><span class="line"></span><br><span class="line">                            getDoctRedInfo(esDoctorRecord, doctorRedExportVo);</span><br><span class="line"></span><br><span class="line">                        &#125;);</span><br><span class="line"></span><br><span class="line">                CompletableFuture&lt;Void&gt; f2 = CompletableFuture</span><br><span class="line"></span><br><span class="line">                        .runAsync(() -&gt; &#123;</span><br><span class="line"></span><br><span class="line">                            BASFI_ASAS_HI(esDoctorRecord, doctorRedExportVo);</span><br><span class="line"></span><br><span class="line">                        &#125;);</span><br><span class="line"></span><br><span class="line">                CompletableFuture&lt;Void&gt; f3 = CompletableFuture</span><br><span class="line"></span><br><span class="line">                        .runAsync(() -&gt; &#123;</span><br><span class="line"></span><br><span class="line">                            yearQuestion(esDoctorRecord, doctorRedExportVo);</span><br><span class="line"></span><br><span class="line">                        &#125;);</span><br><span class="line"></span><br><span class="line">                CompletableFuture&lt;Void&gt; f4 = CompletableFuture</span><br><span class="line"></span><br><span class="line">                        .runAsync(() -&gt; &#123;</span><br><span class="line"></span><br><span class="line">                            asdas(esDoctorRecord, doctorRedExportVo);</span><br><span class="line"></span><br><span class="line">                        &#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">//                getDoctRedInfo(esDoctorRecord, doctorRedExportVo);</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//                BASFI_ASAS_HI(esDoctorRecord, doctorRedExportVo);</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//                yearQuestion(esDoctorRecord, doctorRedExportVo);</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//                asdas(esDoctorRecord, doctorRedExportVo);</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//                CompletableFuture.allOf(f1,f2,f3,f4).join();</span></span><br><span class="line"></span><br><span class="line"> </span><br><span class="line"></span><br><span class="line">                tDoctorRecords.add(doctorRedExportVo);</span><br><span class="line"></span><br><span class="line"><span class="comment">//            &#125;</span></span><br><span class="line"></span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<ul>
<li>CountDownLatch</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">export</span><span class="params">(<span class="keyword">int</span> exportType, Long livingId, String timeRange, HttpServletRequest request, HttpServletResponse response)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//改为从es获取医生记录</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">long</span> start1 = System.currentTimeMillis();</span><br><span class="line"></span><br><span class="line">        List&lt;ESDoctorRecord&gt; tDoctorRecord = exportHelp.getTDoctorRecord(livingId);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (CollectionUtils.isEmpty(tDoctorRecord)) &#123;</span><br><span class="line"></span><br><span class="line">            ExportUtils.responseData(response);</span><br><span class="line"></span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">long</span> start2 = System.currentTimeMillis();</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;查询1，耗时：&quot;</span> + (start2 - start1) + <span class="string">&quot;ms&quot;</span>);</span><br><span class="line"></span><br><span class="line">        Result&lt;List&lt;UserAndPatientVo&gt;&gt; produceResultModel = tUserInterface.ExportPatient(livingId);</span><br><span class="line"></span><br><span class="line">        List&lt;UserAndPatientVo&gt; patientData = produceResultModel.getData();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (CollectionUtils.isEmpty(tDoctorRecord) || CollectionUtils.isEmpty(patientData)) &#123;</span><br><span class="line"></span><br><span class="line">            ExportUtils.responseData(response);</span><br><span class="line"></span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        tDoctorRecord = tDoctorRecord.stream().filter(a -&gt; !Constant.TEST_HOSPITAL.contains(a.getHospitalId())).collect(Collectors.toList());</span><br><span class="line"></span><br><span class="line">        System.out.println(tDoctorRecord.size() + <span class="string">&quot;----&quot;</span>);</span><br><span class="line"></span><br><span class="line">        Map&lt;Long, List&lt;UserAndPatientVo&gt;&gt; patientMap = patientData.stream().collect(Collectors.groupingBy(UserAndPatientVo::getUserId));</span><br><span class="line"></span><br><span class="line">        <span class="comment">//按照患者id分组，组内按照就诊时间升序</span></span><br><span class="line"></span><br><span class="line">        Map&lt;Long, List&lt;ESDoctorRecord&gt;&gt; patientIdGroupMap = tDoctorRecord.stream().collect(Collectors.groupingBy(ESDoctorRecord::getUserId));</span><br><span class="line"></span><br><span class="line">        <span class="comment">//注意！！多线程写</span></span><br><span class="line"></span><br><span class="line">        List&lt;DoctorRedExportVo&gt; tDoctorRecords = Collections.synchronizedList(<span class="keyword">new</span> ArrayList&lt;&gt;());</span><br><span class="line"></span><br><span class="line">        <span class="keyword">long</span> start = System.currentTimeMillis();</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;查询2，耗时：&quot;</span> + (start - start1) + <span class="string">&quot;ms&quot;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//        for (Map.Entry&lt;Long, List&lt;ESDoctorRecord&gt;&gt; entry : patientIdGroupMap.entrySet()) &#123;</span></span><br><span class="line"></span><br><span class="line">        List&lt;Map&lt;Long, List&lt;ESDoctorRecord&gt;&gt;&gt; maps = CollUtils.mapChunk(patientIdGroupMap, patientIdGroupMap.size() / <span class="number">15</span>+<span class="number">1</span>);</span><br><span class="line"></span><br><span class="line">        CountDownLatch countDownLatch = <span class="keyword">new</span> CountDownLatch(maps.size() );</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (Map&lt;Long, List&lt;ESDoctorRecord&gt;&gt; m : maps) &#123;</span><br><span class="line"></span><br><span class="line">            excelEventPool.submit(<span class="keyword">new</span> Runner(livingId, patientMap, m, tDoctorRecords, countDownLatch));</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line"></span><br><span class="line">            countDownLatch.await();</span><br><span class="line"></span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line"></span><br><span class="line">            e.printStackTrace();</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line"> </span><br><span class="line"></span><br><span class="line">        <span class="comment">//用定长线程池会死锁!!</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//        CyclicBarrier cyclicBarrier = new CyclicBarrier(maps.size() + 1);</span></span><br><span class="line"></span><br><span class="line"> </span><br><span class="line"></span><br><span class="line"><span class="comment">//        for (Map&lt;Long, List&lt;ESDoctorRecord&gt;&gt; m : maps) &#123;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//            excelEventPool.submit(new Runner(livingId, patientMap, m, tDoctorRecords, cyclicBarrier));</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//            new Thread(new Runner(livingId, patientMap, m, tDoctorRecords, cyclicBarrier)).start();</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//        &#125;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//        maps.parallelStream().map(n-&gt;&#123;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//            new Thread(new Runner(livingId, patientMap, n, tDoctorRecords, cyclicBarrier)).start();</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//            return null;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//        &#125;);</span></span><br><span class="line"></span><br><span class="line"> </span><br><span class="line"></span><br><span class="line"><span class="comment">//        try &#123;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//            cyclicBarrier.await();</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//        &#125; catch (InterruptedException e) &#123;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//            e.printStackTrace();</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//        &#125; catch (BrokenBarrierException e) &#123;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//            e.printStackTrace();</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//        &#125;</span></span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;-----------\n所有thread执行完成！&quot;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//        cal(livingId, patientMap, patientIdGroupMap, tDoctorRecords);</span></span><br><span class="line"></span><br><span class="line">        System.out.println(tDoctorRecords.size() + <span class="string">&quot;--===--&quot;</span>);</span><br><span class="line"></span><br><span class="line">        tDoctorRecords.sort(Comparator.comparing(DoctorRedExportVo::getUserId).thenComparing(DoctorRedExportVo::getVisitTime));</span><br><span class="line"></span><br><span class="line">        <span class="keyword">long</span> end = System.currentTimeMillis();</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;方法，耗时：&quot;</span> + (end - start) + <span class="string">&quot;ms&quot;</span>);</span><br><span class="line"></span><br><span class="line">        export(request, response, tDoctorRecords);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">long</span> end2 = System.currentTimeMillis();</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;方法2，耗时：&quot;</span> + (end2 - end) + <span class="string">&quot;ms&quot;</span>);</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;总，耗时：&quot;</span> + (end2 - start1) + <span class="string">&quot;ms&quot;</span>);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"> </span><br><span class="line"></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Runner</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">private</span> CountDownLatch countDownLatch;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">private</span> Long livingId;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">private</span> Map&lt;Long, List&lt;UserAndPatientVo&gt;&gt; patientMap;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">private</span> Map&lt;Long, List&lt;ESDoctorRecord&gt;&gt; patientIdGroupMap;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">private</span> List&lt;DoctorRedExportVo&gt; tDoctorRecords;</span><br><span class="line"></span><br><span class="line"> </span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">Runner</span><span class="params">(Long livingId, Map&lt;Long, List&lt;UserAndPatientVo&gt;&gt; patientMap, Map&lt;Long, List&lt;ESDoctorRecord&gt;&gt; patientIdGroupMap, List&lt;DoctorRedExportVo&gt; tDoctorRecords, CountDownLatch countDownLatch)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">this</span>.countDownLatch = countDownLatch;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">this</span>.livingId = livingId;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">this</span>.patientMap = patientMap;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">this</span>.patientIdGroupMap = patientIdGroupMap;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">this</span>.tDoctorRecords = tDoctorRecords;</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line"> </span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line"></span><br><span class="line">                cal(livingId, patientMap, patientIdGroupMap, tDoctorRecords);</span><br><span class="line"></span><br><span class="line"><span class="comment">//                countDownLatch.await();</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//                System.out.println(Thread.currentThread().getName() + &quot;结束&quot;);</span></span><br><span class="line"></span><br><span class="line">            &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line"></span><br><span class="line">                countDownLatch.countDown();</span><br><span class="line"></span><br><span class="line">                System.out.println(Thread.currentThread().getName() + <span class="string">&quot;结束&quot;</span>);</span><br><span class="line"></span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line"> </span><br><span class="line"></span><br><span class="line"> </span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
      </div>
      <div class="post-tags-categories">
        
        <div class="tags">
          
            <a href="/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" class="">
              多线程
            </a>
          
            <a href="/tags/CountDownLatch/" class="">
              CountDownLatch
            </a>
          
            <a href="/tags/CompletableFuture/" class="">
              CompletableFuture
            </a>
          
        </div>
        
      </div>
      
        <div class="copyright">
  <ul class="post-copyright">
    <li class="post-copyright-author">
    <strong>作者:  </strong>symkmk123</a>
    </li>
    <li class="post-copyright-link">
    <strong>文章链接:  </strong>
    <a href="/2022/02/14/java多线程加速遍历解析/" target="_blank" title="java多线程加速遍历解析">http://example.com/2022/02/14/java多线程加速遍历解析/</a>
    </li>
    <li class="post-copyright-license">
      <strong>版权声明:   </strong>
      本网站所有文章除特别声明外,均采用 <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">CC BY-NC-ND 4.0</a>
      许可协议。转载请注明出处!
    </li>
  </ul>
<div>
      
    </article>
    <!-- 上一篇文章和下一篇文章 -->
    
      <!-- 文章详情页的上一页和下一页 -->
<div class="post-nav">



  
  <div class="post-nav-prev post-nav-item">
    <div class="post-nav-img" style="background-size: cover; 
      background-position: center center;">
      <img class="lazyload lazyload placeholder" src="/medias/1.jpg" class="lazyload placeholder" data-srcset="/medias/1.jpg" srcset="https://img2.baidu.com/it/u=2037979560,2772131037&fm=26&fmt=auto&gp=0.jpg" alt="">
    </div>
    <a href="/2022/02/14/Elasticsearch%E4%B8%ADScript%E7%94%A8%E6%B3%95%E4%BB%A3%E6%9B%BFsql%E4%B8%ADa%E5%B0%8F%E4%BA%8Eb%E6%9D%A1%E4%BB%B6/" class="post-nav-link">
      <div class="title">
        <i class="fas fa-angle-left"></i> 上一篇:
        <div class="title-text">Elasticsearch中Script用法代替sql中a小于b条件</div>
      </div>
      
      <!-- <div class="content">
        Elasticsearch中Script用法代替sql中a小于b条件如果real_follow_time为空，判断条件为
      </div> -->
    </a>
  </div>



  
  <div class="post-nav-next post-nav-item">
    <div class="post-nav-img" style="background-size: cover; 
      background-position: center center;">
      <img class="lazyload lazyload placeholder" src="/medias/11.jpg" class="lazyload placeholder" data-srcset="/medias/11.jpg" srcset="https://img2.baidu.com/it/u=2037979560,2772131037&fm=26&fmt=auto&gp=0.jpg" src="" alt="">
    </div>
    <a href="/2021/10/20/02redis%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81%E5%88%86%E6%9E%90%E4%B8%8Ecluster%E6%A8%A1%E5%BC%8F%E6%90%AD%E5%BB%BA/" class="post-nav-link">
      <div class="title">
        下一篇: <i class="fas fa-angle-right"></i>
        <div class="title-text">02redis分布式锁分析与cluster模式搭建</div>
      </div>
      <!-- <div class="content">
        1.redis分布式锁的问题
第一种方案，基于redis单实例，不靠谱，因为redis单点故障，会导致系统全盘崩溃，做不
      </div> -->
    </a>
  </div>

</div>

    
    

    <!-- 打赏 -->
    

    <!-- 分享 -->
    
    
    <!-- 评论 -->
    <!-- 评论 -->

  <div id="myComment">
    
      <div id="gitment-container"></div>

    
  </div>

<!-- comment script in themes\hexo-theme-bamboo\layout\_partial\scripts\index.ejs -->


  </div>

  <!-- 目录 -->
  <!-- 文章详情页右侧目录 -->

  <div class="toc-aside">
    <div class="toc-main">
      <div class="toc-aside-title">
        <i class="fas fa-list-ul" aria-hidden="true"></i><span>本文目录</span>
        
          <div class="toc-open-close">本文目录</div>
        
      </div>
      <div class="toc-content">
        <div class="toc"></div>
      </div>
    </div>
  </div>

  <!-- 手机端目录按钮 -->
  <div id="toc-mobile-btn">
    <i class="fas fa-list-ul" aria-hidden="true"></i>
  </div>
  <!-- js在scripts目录下的的toc.ejs里面 -->
  

  <script>
    function openBtnClickFn () {
      let openOrCloseBtn = $('.toc-aside .toc-aside-title .toc-open-close');
      let open = eval('' || 'true');
      openOrCloseBtn.click(function() {
        if (open === true) {
          $(".toc-aside").css({'width': 0, 'padding': 0});
          $(".toc-content").css({'width': 0});
          $(".toc-aside-title span, .toc-aside-title i").css({'display': 'none'});
          $(".main-content").css({'width': '75%', 'margin': '10px auto'});
          open = false;
        } else {
          $(".toc-aside").css({'width': '300px', 'padding': '0 10px'});
          $(".toc-content").css({'width': '300px'});
          $(".toc-aside-title span, .toc-aside-title i").css({'display': 'inline-block'});
          $(".main-content").css({'width': '65%', 'margin-right': '10px', 'margin-left': 'calc(35% - 350px)'});
          open = true;
        }
      });
    };
    openBtnClickFn();
    document.addEventListener('pjax:complete', function () {
      openBtnClickFn();
    })
    
  </script>


  <!-- 图片放大 Wrap images with fancybox support -->
  <script src="/js/wrapImage.js"></script>
</div>

<!-- 文章详情页背景图 -->
<div id="appBgSwiper" style="position: fixed;left: 0;top: 0;width: 100%;height: 100%;z-index: -2;"
	:style="{'background-color': bgColor ? bgColor : 'transparent'}">
	<transition-group tag="ul" :name="names">
		<li v-for='(image,index) in img' :key='index' v-show="index === mark" class="bg-swiper-box">
			<img :src="image" class="bg-swiper-img no-lazy">
		</li>
	</transition-group>
</div>
<script>
	var vm = new Vue({
		el: '#appBgSwiper',
		data: {
			names: '' || 'fade' || 'fade', // translate-fade fade
			mark: 0,
			img: [],
			bgColor: '',
			time: null
		},
		methods: {   //添加方法
			change(i, m) {
				if (i > m) {
					// this.names = 'fade';
				} else if (i < m) {
					// this.names = 'fade';
				} else {
					return;
				}
				this.mark = i;
			},
			prev() {
				// this.names = 'fade';
				this.mark--;
				if (this.mark === -1) {
					this.mark = 3;
					return
				}
			},
			next() {
				// this.names = 'fade';
				this.mark++;
				if (this.mark === this.img.length) {
					this.mark = 0;
					return
				}
			},
			autoPlay() {
				// this.names = 'fade';
				this.mark++;
				if (this.mark === this.img.length) {
					this.mark = 0;
					return
				}
			},
			play() {
				let bgImgDelay = '' || '180000'
				let delay = parseInt(bgImgDelay) || 180000;
				this.time = setInterval(this.autoPlay, delay);
			},
			enter() {
				clearInterval(this.time);
			},
			leave() {
				this.play();
			}
		},
		created() {
			this.play()
		},
		beforeDestroy() {
			clearInterval(this.time);
		},
		mounted() {
			let prop = '' || '';
			let isImg = prop.includes('.bmp') || prop.includes('.jpg') || prop.includes('.png') || prop.includes('.tif') || prop.includes('.gif') || prop.includes('.pcx') || prop.includes('.tga') || prop.includes('.exif') || prop.includes('.fpx') || prop.includes('.psd') || prop.includes('.cdr') || prop.includes('.pcd') || prop.includes('.dxf') || prop.includes('.ufo') || prop.includes('.eps') || prop.includes('.ai') || prop.includes('.raw') || prop.includes('.WMF') || prop.includes('.webp') || prop.includes('.jpeg') || prop.includes('http://') || prop.includes('https://')
			if (isImg) {
				let img = prop.split(',');
				let configRoot = '/'
				let arrImg = [];
				img.forEach(el => {
					var Expression = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
					var objExp = new RegExp(Expression);

					if (objExp.test(el)) {
						// http or https
						arrImg.push(el);
					} else {
						// 非http or https开头
						// 本地文件
						let firstStr = el.charAt(0);
						if (firstStr == '/') {
							el = el.substr(1); // 删除第一个字符 '/',因为 configRoot最后一个字符为 /
						}
						el = configRoot + el;
						arrImg.push(el);
					}
				})
				this.img = arrImg;
			} else {
				this.bgColor = prop;
			}
		}
	})
</script>

<style>
	.bg-swiper-box {
		position: absolute;
		display: block;
		width: 100%;
		height: 100%;
	}

	.bg-swiper-img {
		object-fit: cover;
		width: 100%;
		height: 100%;
	}
</style>




  <script>
  function loadMermaid() {
    if (document.getElementsByClassName('mermaid').length) {
      if (window.mermaidJsLoad) mermaid.init()
      else {
        loadScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
          window.mermaidJsLoad = true
          mermaid.initialize({
            theme: 'default',
          })
          if ('true') {
            mermaid.init();
          }
        })
      }
    }
  };
  document.addEventListener("DOMContentLoaded", function () {
    loadMermaid();
  })

  document.addEventListener('pjax:complete', function () {
    loadMermaid();
  })
  
</script>


      </main>
    </div>

    <!-- 页脚 -->
    
  
  <div class="footer bg-color">
    <div class="footer-main">
      
        
          <div class="link">
            
          </div>
        
      
        
          <div class="footer-copyright">
            <p>Copyright © 2019 - 2020 <a target="_blank" rel="noopener" href="https://github.com/yuang01">yuang01</a> | Powered by <a target="_blank" rel="noopener" href="https://hexo.io/zh-cn/docs/">Hexo</a> | Theme <a target="_blank" rel="noopener" href="https://github.com/yuang01/theme">Bamboo</a> </p>

          </div>
        
      
        
          
            <!-- 不蒜子统计 -->
            <!-- 不蒜子统计 -->
<span id="busuanzi_container_site_pv">
      <i class="fas fa-eye" aria-hidden="true"></i>本站总访问量：<span id="busuanzi_value_site_pv"></span> 次
</span>
<span class="post-meta-divider">|</span>
<span id="busuanzi_container_site_uv" style='display:none'>
      <i class="fas fa-users" aria-hidden="true"></i>本站访客数：<span id="busuanzi_value_site_uv"></span> 人
</span>

          
        
      
        
          <div class="footer-custom">
            
          </div>
        
      
    </div>
  </div>



    <!-- 渲染暗黑按钮 -->
    
      <div class="dark">
  <div class="dark-content">
    <i class="fas fa-moon" aria-hidden="true"></i>
    <!-- <span>关灯</span> -->
  </div>
  
</div>

<script>
  $(function() {
    let isDark = JSON.parse(localStorage.getItem('dark'))  || JSON.parse('false');
    if (isDark) {
      $(".dark-content").replaceWith(
          `
          <div class='dark-content'>
            <i class="fas fa-lightbulb" aria-hidden="true"></i>
          </div>
          `
        );
    }
    $('.dark').click(function() {
      if ($(document.body).is('.darkModel')) {
        $(document.body).removeClass('darkModel');
        localStorage.setItem('dark', false);
        $(".dark-content").replaceWith(
          `
          <div class='dark-content'>
            <i class="fas fa-moon" aria-hidden="true"></i>
          </div>
          `
        );
      } else {
        $(document.body).addClass('darkModel');
        localStorage.setItem('dark', true);
        $(".dark-content").replaceWith(
          `
          <div class='dark-content'>
            <i class="fas fa-lightbulb" aria-hidden="true"></i>
          </div>
          `
        );
      }
    })
  })
</script>
    
    <!-- 渲染回到顶部按钮 -->
    
      <div class="goTop top-btn-color" pointer>
  <i class="fas fa-arrow-up" aria-hidden="true"></i>
</div>
<script src="/js/goTop.js"></script>

    
    <!-- 渲染左下角音乐播放器 -->
    

    <!-- 图片放大 -->
    
      <script src="/js/fancybox/jquery.fancybox.min.js"></script>
    

    <!-- 百度解析 -->
    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <!-- 背景彩带 -->
    
      <script type="text/javascript" size="100" alpha='0.4' zIndex="-1" src="/js/ribbon.min.js"></script>
    

    <script src="/js/utils/index.js"></script>
    <script src="/js/app.js" data-pjax></script>
    
    <!-- 文章目录所需js -->
<link href="/js/tocbot/tocbot.css" rel="stylesheet">
<script src="/js/tocbot/tocbot.min.js"></script>

<script>
  var headerEl = 'h1,h2, h3, h4',  //headers 
    content = '.post-detail',//文章容器
    idArr = {};  //标题数组以确定是否增加索引id
  //add #id
  var option = {
    // Where to render the table of contents.
    tocSelector: '.toc',
    // Where to grab the headings to build the table of contents.
    contentSelector: content,
    // Which headings to grab inside of the contentSelector element.
    headingSelector: headerEl,
    scrollSmooth: true,
    scrollSmoothOffset: -80,
    headingsOffset: -($(window).height() * 0.4 - 45),
    positionFixedSelector: '.toc-main',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto',
    activeLinkClass: 'is-active-link',
    // onClick: function (e) {},
  }
  if ($('.toc').length > 0) {

    $(content).children(headerEl).each(function () {
      //去除空格以及多余标点
      var headerId = $(this).text().replace(/[\s|\~|`|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\_|\+|\=|\||\|\[|\]|\{|\}|\;|\:|\"|\'|\,|\<|\.|\>|\/|\?|\：|\，|\。]/g, '');

      headerId = headerId.toLowerCase();
      if (idArr[headerId]) {
        //id已经存在
        $(this).attr('id', headerId + '-' + idArr[headerId]);
        idArr[headerId]++;
      }
      else {
        //id未存在
        idArr[headerId] = 1;
        $(this).attr('id', headerId);
      }
    });

    document.addEventListener("DOMContentLoaded", function () {
      tocbot.init(option);
      mobileTocClick();
    });

  }

  window.tocScrollFn = function () {
    return bamboo.throttle(function () {
      findHeadPosition();
    }, 100)()
  }
  window.addEventListener('scroll', tocScrollFn);

  const findHeadPosition = function (top) {
    if ($('.toc-list').length <= 0) {
      return false;
    }
    setTimeout(() => {  // or DOMContentLoaded 
      autoScrollToc();
    }, 0);
  }

  const autoScrollToc = function () {
    const $activeItem = document.querySelector('.is-active-link');
    const $cardToc = document.querySelector('.toc-content');
    const activePosition = $activeItem.getBoundingClientRect().top
    const sidebarScrollTop = $cardToc.scrollTop
    if (activePosition > (document.documentElement.clientHeight - 100)) {
      $cardToc.scrollTop = sidebarScrollTop + 150
    }
    if (activePosition < 100) {
      $cardToc.scrollTop = sidebarScrollTop - 150
    }
  }

  document.addEventListener('pjax:send', function () {
    if ($('.toc').length) {
      tocbot.destroy();
    }
  });

  document.addEventListener('pjax:complete', function () {
    if ($('.toc').length) {
      tocbot.init(option);
      mobileTocClick();
    }
  });
  
  // 手机端toc按钮点击出现目录
  const mobileTocClick = function () {
    const $cardTocLayout = document.getElementsByClassName('toc-aside')[0];
    const $cardToc = $cardTocLayout.getElementsByClassName('toc-content')[0];
    let right = '45px';
    if (window.innerWidth >= 551 && window.innerWidth <= 992) {
      right = '100px'
    }
    const mobileToc = {
      open: () => {
        $cardTocLayout.style.cssText = 'animation: toc-open .3s; opacity: 1; right: ' + right
      },

      close: () => {
        $cardTocLayout.style.animation = 'toc-close .2s'
        setTimeout(() => {
          $cardTocLayout.style.cssText = "opacity:''; animation: ''; right: ''"
        }, 100)
      }
    }
    document.getElementById('toc-mobile-btn').addEventListener('click', () => {
      if (window.getComputedStyle($cardTocLayout).getPropertyValue('opacity') === '0') mobileToc.open()
      else mobileToc.close()
    })

    $cardToc.addEventListener('click', (e) => {
      if (window.innerWidth < 992) { // 小于992px的时候
        mobileToc.close()
      }
    })
  }
</script>

<style>
  .is-position-fixed {
    position: sticky !important;
    top: 74px;
  }

  .toc-main ul {
    counter-reset: show-list;
  }

  .toc-main ul li::before {
    content: counter(item)".";
    display: block;
    position: absolute;
    left: 12px;
    top: 0;
  }
</style> 

<!-- 渲染issues标签里的内容 -->
<script>
  function loadIssuesJS() {
    if ($(".post-detail").find(".issues-api").length == 0) {
      return;
    } 
    loadScript('/js/issues/index.js');
  };
  $(function () {
    loadIssuesJS();
  });
  document.addEventListener('pjax:complete', function () {
    if (typeof IssuesAPI == "undefined") {
      loadIssuesJS();
    }
  })
</script>

<!-- 输入框打字特效 -->
<!-- 输入框打字特效 -->

  <script src="/js/activate-power-mode.js"></script>
  <script>
    POWERMODE.colorful = true;  // 打开随机颜色特效
    POWERMODE.shake = false;    // 关闭输入框抖动
    document.body.addEventListener('input', POWERMODE);//监听打字事件
  </script>


<!-- markdown代码一键复制功能 -->

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/v-plugs-ayu/lib/ayu.css">
  <script src="https://cdn.jsdelivr.net/npm/v-plugs-ayu/lib/ayu.umd.min.js"></script>
  <script src="/js/clipboard/clipboard.min.js"></script>
  <div id="appCopy">
  </div>
  <script data-pjax>
    var vm = new Vue({
      el: '#appCopy',
      data: {
      },
      computed: {
      },
      mounted() {
        const that = this;
        var copy = '复制';
        /* code */
        var initCopyCode = function () {
          var copyHtml = '';
          copyHtml += '<button class="btn-copy" data-clipboard-snippet="" style="position:absolute;top:0;right:0;z-index:1;">';
          copyHtml += '<i class="fas fa-copy"></i><span>' + copy + '</span>';
          copyHtml += '</button>';
          $(".post-detail pre").not('.gutter pre').wrap("<div class='codeBox' style='position:relative;width:100%;'></div>")
          $(".post-detail pre").not('.gutter pre').before(copyHtml);
          new ClipboardJS('.btn-copy', {
            target: function (trigger) {
              return trigger.nextElementSibling;
            }
          });
        }
        initCopyCode();
        $('.btn-copy').unbind('click').bind('click', function () {
          doSomething();
        })
        $(document).unbind('keypress').bind('keypress', function (e) {
          if (e.ctrlKey && e.keyCode == 67) {
            doSomething();
          }
        })

        function doSomething() {
          that.$notify({
            title: "成功",
            content: "代码已复制，请遵守相关授权协议。",
            type: 'success'
          })
        }
      },
      methods: {
      },
      created() { }
    })
  </script>
  

<!-- 图片懒加载 -->
<script defer src="https://cdn.jsdelivr.net/npm/vanilla-lazyload@17.1.0/dist/lazyload.min.js"></script>
<script>
  // https://www.npmjs.com/package/vanilla-lazyload
  // Set the options globally
  // to make LazyLoad self-initialize
  window.lazyLoadOptions = {
    elements_selector: ".lazyload",
    threshold: 0
  };
  // Listen to the initialization event
  // and get the instance of LazyLoad
  window.addEventListener(
    "LazyLoad::Initialized",
    function (event) {
      window.lazyLoadInstance = event.detail.instance;
    },
    false
  );
  document.addEventListener('DOMContentLoaded', function () {
    lazyLoadInstance.update();
  });
  document.addEventListener('pjax:complete', function () {
    lazyLoadInstance.update();
  });
</script>


<!-- 卡片滚动动画 -->
   

<!-- 评论所需js -->

  
    <script type="text/javascript">
  var utteranceCommon = {};

  function check_utterance() {
    let isDark = JSON.parse(localStorage.getItem('dark')) || JSON.parse('false');
    if (isDark) {
      utteranceCommon.Theme = 'github-dark';
    } else {
      utteranceCommon.Theme = 'github-light';
    }

    return document.getElementById("gitment-container");
  }
  comment_el = '#gitment-container';
  load_utterance = function () {
    if ($(comment_el).length) {
      // 匿名函数，防止污染全局变量
      const HEAD = check_utterance();

      var utterances = document.createElement('script');
      utterances.type = 'text/javascript';
      utterances.async = true;
      utterances.setAttribute('issue-term', 'pathname')
      utterances.setAttribute('theme', utteranceCommon.Theme)
      utterances.setAttribute('repo', '')
      utterances.crossorigin = 'anonymous';
      utterances.src = 'https://utteranc.es/client.js';
      // content 是要插入评论的地方
      document.getElementById('gitment-container').appendChild(utterances);

    }
  }

  function dark_utterance() {
    const HEAD = check_utterance();
    if (!HEAD) return;
    const message = {
      type: 'set-theme',
      theme: utteranceCommon.Theme
    };
    const utteranceIframe = document.querySelector('iframe');
    utteranceIframe.contentWindow.postMessage(message, 'https://utteranc.es');
  }

  $(document).ready(load_utterance);
  document.addEventListener('pjax:complete', function () {
    load_utterance();
  });

  $('.dark').click(function () {
    setTimeout(() => {
      dark_utterance();
    });
  })

</script>

<style>
  .utterances {
    max-width: inherit !important;
  }
</style>
  


<!-- 鼠标点击特效 -->
<!-- 爱心点击 -->

  
    <script src="/js/cursor/text.js"></script>
  




  <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" data-pjax></script>


    <!-- pjax -->
    

<!-- pjax -->


  <script src="/js/pjax@0.2.8/index.js"></script>
  
    <!-- 样式位于：source/css/_third-party/pjaxanimate.styl -->

<div class="pjax-animate">
  
    <div class="loading-circle"><div id="loader-circle"></div></div>
    <script>
      window.ShowLoading = function() {
        $(".loading-circle").css("display", "block");
      };
      window.HideLoading = function() {
        $(".loading-circle").css("display", "none");
      }
    </script>
  
	<script>
    document.addEventListener('pjax:complete', function () {
      window.HideLoading();
    })
    document.addEventListener('pjax:send', function () {
      window.ShowLoading();
    })
    document.addEventListener('pjax:error', function () {
      window.HideLoading();
    })
	</script>
</div>

  

  <script>
    var pjax = new Pjax({
      elements: 'a[href]:not([href^="#"]):not([href="javascript:void(0)"]):not([no-pjax])',   // 拦截正常带链接的 a 标签
      selectors: ["#pjax-container","title"],                                   // 根据实际需要确认重载区域
      cacheBust: false,   // url 地址追加时间戳，用以避免浏览器缓存
      timeout: 5000
    });

    document.addEventListener('pjax:send', function (e) {

      try {
        var currentUrl = window.location.pathname;
        var targetUrl = e.triggerElement.href;
        var banUrl = [""];
        if (banUrl[0] != "") {
          banUrl.forEach(item => {
            if(currentUrl.indexOf(item) != -1 || targetUrl.indexOf(item) != -1) {
              window.location.href = targetUrl;
            }
          });
        }
      } catch (error) {}

      $(window).unbind('resize');
      $(window).unbind('scroll');
      $(document).unbind('scroll');
      $(document).unbind('click');
      $('body').unbind('click');

    })
    
    document.addEventListener('pjax:complete', function () {
      $('script[data-pjax], .pjax-reload script').each(function () {
        $(this).parent().append($(this).remove());
      });
    });

    document.addEventListener('pjax:error', function (e) {
      window.location.href = e.triggerElement.href;
    })
    
    // 刷新不从顶部开始
    document.addEventListener("DOMContentLoaded", function () {
      history.scrollRestoration = 'auto';
    })
  </script>



  </body>
</html>